﻿using KPIS.GERP.Models;
using KPIS.GERP.Models.Class;
using KPIS.GERP.Models.ICM;
using KPIS.GERP.Models.ICM.ViewModel;
using KPIS.GERP.Models.SYS;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Linq.Dynamic;
using System.ServiceModel;
using System.Web.Mvc;

namespace KPIS.GERP.WCF.GIMS
{
    [ServiceContract]
    public interface IAssetService
    {
        [OperationContract]
        IEnumerable<Asset> Select(Asset filter);

        [OperationContract]
        List<SelectListItem> SelectListAsset(int? AssetId);

        [OperationContract]
        List<SelectListItem> SelectListQuantity(int? AssetId);

        [OperationContract]
        IEnumerable<KPIS.GERP.Models.ICM.Asset> SelectAsset(Asset criteriaModel = null, List<string> includeSubObjectString = null);

        [OperationContract]
        List<Asset> ParcelControlAssetList();

        [OperationContract]
        int InsertPictureAsset(Asset model, int updateByUserId);

        [OperationContract]
        IEnumerable<KPIS.GERP.Models.ICM.Asset> SelectAssetDetail(Asset criteriaModel = null, List<string> includeSubObjectString = null);

        [OperationContract]
        List<SelectListItem> SelectListWhAsset(int? WhId, int? assetId);

        [OperationContract]
        List<SelectListItem> SelectListJsAsset(int? jobSite, int? assetId);

        [OperationContract]
        int UpdateMovementAsset(Asset model, int updateByUserId);

        // ราคาครุภัณฑ์ปัจจุบัน ( คิดจากค่าเสื่อมตาราง IcmAssetDepreciated )
        [OperationContract]
        double? GetCurrentPrice(int AssetId);
    }

    [ServiceErrorBehavior(typeof(ElmahErrorHandler))]
    public class AssetService : IAssetService
    {
        GERPContext db = new GERPContext();
        
        public IEnumerable<Asset> Select(Asset filter)
        {
            return null;
        }

        public List<SelectListItem> SelectListAsset(int? AssetId)
        {
            var list = new List<SelectListItem>();
            list.Add(new SelectListItem { Selected = true, Text = "....เลือกรายการพัสดุ....", Value = "" });

            try
            {
                List<Models.ICM.Asset> listAssets = (from m in db.Assets
                                                         where m.RecordStatus != Models.SYS.RecordStatus.DeletedStatus
                                                         select m).ToList();

                foreach (var asset in listAssets)
                {
                    var item = new SelectListItem { Text = asset.AssetName, Value = asset.AssetId.ToString() };
                    if (asset.AssetId == AssetId) item.Selected = true;
                    list.Add(item);
                }

            }
            catch (Exception ex)
            {
                throw ex;
            }

            return list;
        }

        public List<SelectListItem> SelectListQuantity(int? AssetId)
        {
            var data = new List<SelectListItem>();

            try
            {
                List<Models.ICM.Asset> listAssets = (from m in db.Assets
                                                     where m.RecordStatus != Models.SYS.RecordStatus.DeletedStatus
                                                     select m).ToList();

                foreach (var asset in listAssets)
                {
                    var item = new SelectListItem { Text =  asset.Quantity.ToString(), Value = asset.AssetId.ToString() };
                    if (asset.AssetId == AssetId) item.Selected = true;
                    data.Add(item);
                }

            }
            catch (Exception ex)
            {
                throw ex;
            }

            return data;
        }


        public IEnumerable<KPIS.GERP.Models.ICM.Asset> SelectAsset(Asset criteriaModel = null , List<string> includeSubObjectString = null)
        {
            try
            {
                using (var context = new GERPContext(false))
                {
                    IQueryable<Asset> query = context.Assets;

                    if (includeSubObjectString != null)
                    {
                        query = includeSubObjectString.Aggregate(query, (current, includePath) => current.Include(includePath));
                    }

                    if (criteriaModel != null)
                    {
                        object[] param;
                        query = query.Where(KPIS.GERP.Models.Class.Utility.GenerateWhereString(criteriaModel, out param), param);
                    }

                    return query.ToList();
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        public IEnumerable<KPIS.GERP.Models.ICM.Asset> SelectAssetDetail(Asset criteriaModel = null, List<string> includeSubObjectString = null)
        {
            try
            {
                using (var context = new GERPContext(false))
                {
                    IQueryable<Asset> query = context.Assets;//.Include("MasResourceGroup.MasResourceType");

                    if (includeSubObjectString != null)
                    {
                        query = includeSubObjectString.Aggregate(query, (current, includePath) => current.Include(includePath));
                    }

                    if (criteriaModel != null)
                    {
                        object[] param;
                        query = query.Where(KPIS.GERP.Models.Class.Utility.GenerateWhereString(criteriaModel, out param), param);
                    }

                    return query.ToList();
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        public List<Asset> ParcelControlAssetList ()
        {
            using (var context = new GERPContext(false))
            {
                var data = (from a in context.Assets
                            join b in context.MasResourceTypes on a.AssetTypeId equals b.ResTypeId
                            where a.AssetTypeId == b.ResTypeId
                            select new Asset() { AssetId = (a.AssetId), AssetName = (a.AssetName), Quantity = (a.Quantity), AssetDate = (a.AssetDate) 
                                , AssetCode = (a.AssetCode), WhId = (a.WhId), UnitId = (a.UnitId), AssetTypeId = (a.AssetTypeId), AssetStatusId = (a.AssetStatusId)
                                }).ToList();

                return data;

            }
        }

        public int InsertPictureAsset(Asset model, int updateByUserId)
        {
            try
            {
                using (var context = new GERPContext())
                {
                    context.Entry(model).State = EntityState.Modified;
                    model.UpdatedBy = updateByUserId;
                    model.UpdatedWhen = DateTime.Now;
                    context.SaveChanges();

                    return model.AssetId;
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        public int UpdateMovementAsset(Asset model, int updateByUserId)
        {
            try
            {
                using (var context = new GERPContext())
                {
                    context.Entry(model).State = EntityState.Modified;
                    model.UpdatedBy = updateByUserId;
                    model.UpdatedWhen = DateTime.Now;
                    context.SaveChanges();

                    return model.AssetId;
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }


        public List<SelectListItem> SelectListWhAsset(int? WhId, int? assetId)
        {
            var list = new List<SelectListItem>();
            list.Add(new SelectListItem { Selected = true, Text = "....เลือกรายการพัสดุ....", Value = "" });
            var context = new GERPContext(false);

            try
            {
              List<Models.ICM.Asset> listWhAsset = (from m in db.Assets
                                                      where m.RecordStatus != Models.SYS.RecordStatus.DeletedStatus
                                                      && m.WhId == WhId
                                                      //&& WhId.HasValue ? m.WhId == WhId : true
                                                      && m.JobSiteId == null
                                                      //&& m.JobSiteId.HasValue 
                                                      select m).ToList();

              foreach (var asset in listWhAsset)
              {
                  var item = new SelectListItem { Text = asset.AssetName + " : " + asset.AssetCode, Value = asset.AssetId.ToString() };
                  if (asset.AssetId == assetId) item.Selected = true;
                  list.Add(item);
              }

            }
            catch (Exception ex)
            {
                throw ex;
            }

            return list;
        }

        public List<SelectListItem> SelectListJsAsset(int? jobSiteId, int? assetId)
        {
            var list = new List<SelectListItem>();
            list.Add(new SelectListItem { Selected = true, Text = "....เลือกรายการพัสดุ....", Value = "" });

            try
            {
                List<Models.ICM.Asset> listJsAsset = (from m in db.Assets
                                                      where m.RecordStatus != Models.SYS.RecordStatus.DeletedStatus
                                                      && (jobSiteId.HasValue ? m.JobSiteId == jobSiteId : true)
                                                      select m).ToList();

                foreach (var asset in listJsAsset)
                {
                    var item = new SelectListItem { Text = asset.AssetName + " : " + asset.AssetCode, Value = asset.AssetId.ToString() };
                    if (asset.AssetId == assetId) item.Selected = true;
                    list.Add(item);
                }

            }
            catch (Exception ex)
            {
                throw ex;
            }

            return list;
        }

        // ราคาครุภัณฑ์ปัจจุบัน ( คิดจากค่าเสื่อมตาราง IcmAssetDepreciated )
        public double? GetCurrentPrice(int AssetId)
        {
            var CurrentPrice = (from a in db.Assets
                                where a.AssetId == AssetId
                                && a.RecordStatus != Models.SYS.RecordStatus.DeletedStatus
                                select new
                                {
                                    amount = (double?)a.Price - (double?)db.AssetDepreciations.Where(x => x.AssetId == AssetId).Sum(x => x.DepAmount)
                                }).FirstOrDefault();

            return CurrentPrice != null ? CurrentPrice.amount : null;
        }

    }
}
